//
//  XYWebViewController.swift
//  SinaWB_XY
//
//  Created by 小熊猫 on 15/10/12.
//  Copyright © 2015年 小熊猫. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD

class XYWebViewController: UIViewController, UIWebViewDelegate {

    
    var webView:UIWebView?

    override func viewDidLoad() {
        super.viewDidLoad()

        setupNav()
        
        let webView = UIWebView(frame: UIScreen.mainScreen().bounds)
        webView.delegate = self
        
        //调用网络工具返回登录授权url
        let url = XYSessionManager.sharedManager.loadOAuthUrl()
        printLog(url)
        webView.loadRequest(NSURLRequest(URL: url))
        
        self.view.addSubview(webView)
        self.webView = webView
    }
   
    //添加一个自动填充的按钮
    private func setupNav(){
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoValue")
    }
    
    //实现自动填充按钮的点击事件
    @objc private func autoValue(){
        let script = "document.getElementById('userId').value='15810386040';document.getElementById('passwd').value='Qd520wodeai123'"
        self.webView?.stringByEvaluatingJavaScriptFromString(script)
    }
    
    //webview的代理方法,将要显示界面的时候,加载的网址请求
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //将请求中的网址取出来
        let urlString = request.URL!.absoluteString
        
        if urlString.hasPrefix("https://api.weibo.com"){
            return true
        }
        
        if let query = request.URL?.query{
           
            let codeStr = "code="

            let code =  (query as NSString).substringFromIndex(codeStr.characters.count)
            
            printLog(code)
            
            loadToken(code)
        }
        
        return false
    }
    
    //加载token
    private func loadToken(code:String){
        
        XYSessionManager.sharedManager.loadSinaToken(code){(dict,error) -> () in
            if error != nil{
                SVProgressHUD.showErrorWithStatus("你的网络不给力")
                printLog(error)
                return
            }
            printLog("请求token成功")
            
            //把请求成功之后的字典存起来
            let account = XYWebModel.init(dict: dict!)
            //请求用户信息
                account.loadUserInfo({ (error) -> () in
                    if error != nil{
                        printLog("请求用户信息失败 \(error)")
                        return
                    }else{
                        printLog("请求用户信息成功")
                        let window = UIApplication.sharedApplication().delegate!.window!
                        window?.rootViewController = XYWelcomeVC()
                    }
            })
        }
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}




